/**
 * 
 */
package com.jbarreto.topic.client;

import java.util.Properties;

import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * @author 814168
 *
 */
public class TopicClient {

	/**
	 * @param args
	 * @throws NamingException 
	 */
	public static void main(String[] args) throws Exception {
	
		Properties jndiProps = new Properties();
		jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY,
		"org.jnp.interfaces.NamingContextFactory");
		jndiProps.setProperty(Context.URL_PKG_PREFIXES,
		"org.jboss.naming:org.jnp.interface");
		jndiProps.setProperty(Context.PROVIDER_URL, "jnp://localhost:1099");
		
		InitialContext ctx = new InitialContext(jndiProps);
	
		// 1: Lookup connection factory
        TopicConnectionFactory factory =
            (TopicConnectionFactory) ctx.lookup
                 ("/ConnectionFactory");

        // 2: Use connection factory to create JMS connection
        TopicConnection connection = factory.createTopicConnection();

        // 3: Use connection to create a session
        TopicSession session =
            connection.createTopicSession
                 (false,Session.AUTO_ACKNOWLEDGE);

        // 4: Lookup destination
        Topic topic = (Topic)ctx.lookup("topic/JBTopic");

        // 5: Create a message publisher
        TopicPublisher publisher = session.createPublisher(topic);

        TextMessage msg;
        for (int i = 0; i < 200; i++) {
            // 6: Create and publish a message
            msg = session.createTextMessage();
            msg.setText("This is a test message for Topic MDB. count: " + i);
            publisher.send(msg);
			
		}

        // finish
        publisher.close();
        System.out.println("Message published. Please check application server's console to see the response from MDB.");

        //Close connetion
        connection.close();

	}

}
